package com.bawei.coroutine

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.bawei.coroutine.databinding.ActivityRetrofitBinding
import com.bawei.coroutine.http.ApiResponse
import com.bawei.coroutine.http.ApiService
import com.bawei.coroutine.http.BannerData
import com.bawei.coroutine.http.RetrofitManager
import kotlinx.coroutines.*

class RetrofitActivity : AppCompatActivity() {
    private lateinit var activityRetrofitBinding: ActivityRetrofitBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        activityRetrofitBinding = ActivityRetrofitBinding.inflate(layoutInflater)
        setContentView(activityRetrofitBinding.root)

//        val job = Job()
//        CoroutineScope(job).launch(Dispatchers.Main) {
//            var  result = withContext(Dispatchers.IO){//耗时操作
//                getMessageFromNetwork()
//            }
//            showMessage(result)
//            var result2 = withContext(Dispatchers.IO){//耗时操作
//                getMessageFromNetwork2()
//            }
//            showMessage(result+result2)
//
//        }
        val job = Job()
        CoroutineScope(job).launch(Dispatchers.Main){
            //耗时操作，retrofit默认在子线程中执行，但是ApiService中的方法要被suspend修饰
            val banners = RetrofitManager.getRetrofit().create(ApiService::class.java).getBanners()
            showBanners(banners)//更新UI
        }
    }

    fun showBanners(banners: ApiResponse<List<BannerData>>) {
        if(banners.code == 200){
            activityRetrofitBinding.tv.text = banners.data.toString()
        }
    }
}